package com.myproject.yunPan.ui;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;


import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.myproject.yunPan.common.CronTasks;
import com.myproject.yunPan.common.DirWatcher;
import com.myproject.yunPan.common.constant.CommonConstants;
import com.myproject.yunPan.util.AliYunUtil;
import com.myproject.yunPan.util.ConfigUtil;
import com.myproject.yunPan.util.OkHttpUtil;
import com.myproject.yunPan.util.UpdateUtil;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.json.JSONObject;
import lombok.Data;

/**
 * @author: Mr.chen
 * @date: 2022/2/11 23:07
 * @description: 登录窗口
 */
@Data
public class Login {

	private static final Logger LOG = LogManager.getLogger(Login.class);

    //CK码
    private static String ck;
    //时间戳
    private static String t;

    //当前对象
    private static Login login;

    //初始化对象
    public static Login getInstance() {
        if (login == null) {
            login = new Login();
        }
        return login;
    }

    /**
     * 初始化窗口UI
     */
    public static void initUpdate() {
        login = getInstance();
        LOG.info("检测程序DB是否正常……");
        //检查是否有更新
        if (ConfigUtil.getStartupUpdate()) {
            if (UpdateUtil.checkForUpdate()) UpdateUtil.doUpdateDialog();
        }
        //检查更新程序DB
        UpdateUtil.updateDb();
        //登录
        CommonConstants.LOGIN_STATUS = AliYunUtil.login();
        //窗口切换
        if (CommonConstants.LOGIN_STATUS) {
            LOG.info("登录成功……");
        } else {
            LOG.info("加载二维码……");
            initQrCode();
        }

        //开启定时任务
        ThreadUtil.execute(CronTasks::startTask);
        //开启目录检测
        ThreadUtil.execute(DirWatcher::startWatcher);
    }


    /**
     * 初始化二维码
     */
    public static void initQrCode() {
        login = getInstance();
        //获取二维码
        getQrCodeImg();
        //定时刷新二维码
        new Timer().schedule(new TimerTask() {
            public void run() {

                JSONObject qrCode = OkHttpUtil.queryQrCode(t, ck);
                String status = qrCode.getJSONObject("content").getJSONObject("data").getStr("qrCodeStatus");
                if ("CONFIRMED".equals(status)) {
                    try {
                        JSONObject json = OkHttpUtil.doLogin(qrCode);
                        if (!checkLoginJson(json)) return;
                        String refreshToken = json.getStr("refresh_token");
                        if (StrUtil.isNotEmpty(refreshToken)) {
                            LOG.info("登录成功，正在跳转中，请稍后...");
                            ConfigUtil.setToken(refreshToken);
                            this.cancel();
                            CommonConstants.LOGIN_STATUS = true;
                        }
                    } catch (Exception exc) {
                        LOG.error(exc.getMessage(), "二维码验证错误");
                        return;
                    }
                }
                //二维码过期 刷新二维码
                if ("EXPIRED".equals(status)) {
                    getQrCodeImg();
                }
                if ("SCANED".equals(status)) {
                    LOG.error("已扫描二维码，等待确认...（确认后需等待1-2s）");
                }
            }
        }, 0, 500);
    }

    /**
     * 验证JSON 是否有误
     *
     * @param json
     * @return
     */
    private static boolean checkLoginJson(JSONObject json) {
        if (ObjectUtil.isNotNull(json.getJSONObject("content"))) {
            String titleMsg = json.getJSONObject("content").getJSONObject("data").getStr("titleMsg");
            if (StrUtil.isNotEmpty(titleMsg)) {
                LOG.error("异常错误");
                return false;
            }
            String redirectUrl = json.getJSONObject("content").getJSONObject("data").getStr("iframeRedirectUrl");
            if (StrUtil.isNotEmpty(redirectUrl)) {//异常信息返回
                LOG.error("请您先在电脑网页登录成功后，再登录本软件", "登录错误");
                return false;
            }
        }
        return true;
    }

    /**
     * 获取二维码图片
     */
    private static void getQrCodeImg() {
        login = getInstance();
        JSONObject qrCodeUrl = OkHttpUtil.getQrCodeUrl();
        //二维码地址
        String codeContent = qrCodeUrl.getJSONObject("content").getJSONObject("data").getStr("codeContent");
        ck = qrCodeUrl.getJSONObject("content").getJSONObject("data").getStr("ck");
        t = qrCodeUrl.getJSONObject("content").getJSONObject("data").getStr("t");
        int qrCodeSize = (int) (80);
        byte[] qrCode = QrCodeUtil.generatePng(codeContent, qrCodeSize, qrCodeSize);
        //二维码图片
        try (FileOutputStream fos = new FileOutputStream("erwm.png")) {
            fos.write(qrCode);
            LOG.info("文件保存成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  

}
